/*
 * Copyright (C) 2009 Chang Min Lee <ch5ngmn@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. (/COPYING)
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "IoSessionServerProxy.h"
#include "ServerFinder.h"
#include "IoEventHandler.h"
#include <strstream>
#include <iostream>

IoSessionServerProxy::IoSessionServerProxy (CORBA::ORB_ptr orb, 
																																	PortableServer::POA_ptr poa,
																																	IoEventHandler *handler)
: ServerProxy (orb, poa), handler_(handler)
{
}

int 
IoSessionServerProxy::open (const ACE_TCHAR *server_name, ServerFinder *finder)
{
	CORBA::Object_ptr obj = finder->getRef (server_name);
	if (CORBA::is_nil (obj)) {
		ACE_DEBUG((LM_ERROR, "error: get ref failed\n"));
		return -1;
	}

	session_admin_ = Taonet::SessionAdmin::_narrow(obj);
	if (CORBA::is_nil(session_admin_.in())) {
		ACE_DEBUG((LM_ERROR, "error: get ref failed\n"));
		return -1;
	}
	
	Taonet_CallbackClient_i *cc;
	ACE_NEW_RETURN (cc, Taonet_CallbackClient_i(handler_), -1);
	callback_ = cc;
	callback_oid_ = poa_->activate_object (callback_.in());
	return 0;
}

void
IoSessionServerProxy::process (const ACE_UINT8 *data, ACE_UINT32 length)
{
	try
  {
		Taonet::ByteSeq::value_type * val = (Taonet::ByteSeq::value_type *)data;
		Taonet::ByteSeq_var bytes(length);

		bytes->replace (CORBA::ULong(length), CORBA::ULong(length), val);
		session_->process (bytes);
	}
  catch (const CORBA::Exception& ex)
  {  
    ex._tao_print_exception ("Caught exception:");   
  }
}

int 
IoSessionServerProxy::create_session (const char *id)
{
	session_ = session_admin_->create (id);
	if (CORBA::is_nil (session_.in())) {
		return -1;
	}

  CORBA::Object_var object = poa_->id_to_reference (callback_oid_.in ());
  Taonet::CallbackClient_var callback = 	Taonet::CallbackClient::_narrow (object.in ());
	key_ = session_->login (callback.in());
	
	handler_->OnLogin (key_);
	return 0;
}

void 
IoSessionServerProxy::close ()
{
	if (false == CORBA::is_nil (this->session_.in()) )
	{
		this->session_->logout ();
		handler_->OnLogout(key_);
		key_= 0;
	}
}